<?php

namespace app\common\model\mycurrency;

use think\Model;
use traits\model\SoftDelete;

class UserRechargeOrder extends Model
{

    //use SoftDelete;

    

    // 表名
    protected $name = 'mycurrency_user_recharge_order';

    const STATUS_SHIXIAO = -1;//已支付超时失效
    const STATUS_YIQUXIAO = -2;//已取消
    const STATUS_WEIZHIFU = 1;//未支付
    const STATUS_YIZHIFU = 2;//已支付
    
    /**
     * 获得订单编号
    */
    public static function getOrderSn(){
        $no = date('YmdHis') . rand(10000000, 99999999);
        if (self::where(['order_sn' => $no])->find()) {
            $no = self::getOrderSn();
        }
        return $no;
    }

    /**
     * 订单支付成功后 逻辑处理
     * @param int $order_id 余额充值订单id
    */
    public static function paymentSuccess($order_id){
        $recharge_order = self::where(['id' => $order_id,'deletetime' => null])->lock(true)->find();
        if(!$recharge_order){
            throw new Exception('记录不存在');
            return false;
        }
        if($recharge_order['status'] != self::STATUS_WEIZHIFU){
            throw new Exception('订单非待支付状态');
            return false;
        }

        $recharge_order->status = self::STATUS_YIZHIFU;
        $recharge_order->paymenttime = time();
        $recharge_order->save();

        /**
         * 处理余额变动
         * @param int $user_id 会员ID
         * @param int $money 变动金额
         * @param  int $type 变动类型
         * @param array $data 数据
         */
        $money = $recharge_order['recharge_fee'] + $recharge_order['give_fee'];
        UserMoneyLog::moneyChange($recharge_order['user_id'],$money,UserMoneyLog::TYPE_YONGHUCHONGZHI,[
            'recharge_order_id' => $recharge_order['id'],
            'memo' => '用户余额充值',
        ]);

    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function package()
    {
        return $this->belongsTo('Package', 'package_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
